package com.liyunc.demo.bundle.security.filter;


import com.liyunc.demo.bundle.security.config.properties.JwtConfigurationProperties;
import com.liyunc.demo.bundle.security.model.JwtCredential;
import com.liyunc.demo.comp.auth.AuthenticatedUser;
import com.liyunc.demo.comp.jwt.JwtCodec;
import com.liyunc.demo.comp.jwt.JwtPayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author liyuncong
 * @version 1.0
 * @file JwtAuthProvider.java
 * @brief JwtAuthProvider
 * @details JwtAuthProvider
 * @date 2022-03-31
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-03-31                  liyuncong          Created
 */
@Component
@Slf4j
public class JwtAuthProvider extends AbstractAuthProvider {

    @Autowired
    protected JwtCodec<Object> codec;
    @Autowired
    protected JwtConfigurationProperties config;

    public JwtAuthProvider() {
        super(JwtCredential.class);
    }

    @Override
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {
        if (!(authentication instanceof JwtCredential)) {
            return null;
        }
        JwtCredential credential = (JwtCredential) authentication;
        String jwt = credential.getPrincipal().toString();
        log.debug("Trying to debug token {}", jwt);
        JwtPayload<Object> payload = codec.decode(jwt, config);
        AuthenticatedUser<?> user =
            new AuthenticatedUser<>(
                payload.getLoginUserName(),
                payload.getLoginUserName(),
                payload.getLoginUserId());
        return buildAuthAccount(user);
    }
}
